<?php
if (!defined("_INDEX")) { header("Location: /"); die;}

// function goToPage - change page
function goToPage($url='/'){
	header("Location: $url");
	exit;
}

// function isOnline - check is user online 
function isOnline($user_id){
	global $db;
	$time = $db->getCell("select `last_time` from `users` where `user_id` = '$user_id' limit 1");
	return ($time > time() - TIME_ONLINE);
}

// function cropText - crop $text to $max lenght
function cropText($text,$max=50){
	
	if (mb_strlen($text,"UTF-8") > $max)
		$text = mb_substr($text,0,$max,"UTF-8")."...";
	
	return $text;
}

// function selectCreate - create a select list from $array with value = $key and text = $value and select $compare
function selectCreate($array,$key,$value,$compare="")
{
	$select = "";
	
	foreach ($array as $k=>$val)
	{
		if ($compare != "" && $compare == $val[$key])
			$select .= "<option selected value='".$val[$key]."'>".$val[$value]."</option>";
		else
			$select .= "<option  value='".$val[$key]."'>".$val[$value]."</option>";
	}
	
	return $select;
}

// function randString - generate random string of $len symbols from $alphabet
function randString($len=8,$alphabet="Hsz5Q0@a_Jp1*78FAEWufwkLhGgbVCxZ"){
	$str = "";
	
	for ($i = 0; $i < $len; $i++)
	{
		$symbol_num = rand(0,strlen($alphabet)-1);
		$str .= $alphabet[$symbol_num];
	}
	
	return $str;
}

// function resizeImg - resize $src to $width and $height sizes and save to $path
function resizeImg($src,$width,$height,$path){
	
	$size = getimagesize($src);
	list($type,$ext) = explode("/",$size['mime']);
	if ($type != "image")
		return false;
	
	if ($ext == "jpg") $ext = "jpeg";
	$icf = "imagecreatefrom".$ext;
	if (!function_exists($icf))
		return false;
	
	$source = $icf($src);
	
	if ($size[0] < $width || $size[1] < $height)
		return false;
	if ($size[0] == $width && $size[1] == $height)
	{
		$target = imagecreatetruecolor($width,$height);
		imagecopyresampled($target,$source,0,0,0,0,$width,$height,$width,$height);
		imagejpeg($target,$path,100);
		imagedestroy($source);
		imagedestroy($target);
		
		return true;
	}
	
	$dw = $size[0]/$width; // delta width
	$dh = $size[1]/$height; // delta height
	
	$divider = ($dw < $dh) ? $dw : $dh;
	
	$new_width = $size[0]/$divider;
	$new_height = $size[1]/$divider;
	$plus_width = ($new_width - $width) / 2;
	$plus_height = ($new_height - $height) / 2;
	$target = imagecreatetruecolor($width,$height);
	
	imagecopyresampled(
		$target,  		// Идентификатор нового изображения
		$source,		// Идентификатор исходного изображения
		0,0,      		// Координаты (x,y) верхнего левого угла в новом изображении
		$plus_width*$divider,$plus_height*$divider,		// Координаты (x,y) верхнего левого угла копируемого блока существующего изображения
		$width,				// Новая ширина копируемого блока
		$height,			// Новая высота копируемого блока
		$width*$divider,	// Ширина исходного копируемого блока
		$height*$divider	// Высота исходного копируемого блока
    );
	
	imagejpeg($target, $path, 100);
	
	imagedestroy($source);
	imagedestroy($target);
	
	return true;
}

// function wordEnding - returns word $ending depending on $count $with or without $count
function wordEnding($count,$ending1,$ending2,$ending3,$with=true,$one=true)
{
	if ($count == 1)
		return $one ? $ending1 : "1 $ending1";
	$count = (string)$count;
	$char = (int)$count[strlen($count)-1];
	if ($char == 1)
		$word = $ending1;
	elseif ($char > 1 && $char < 5)
		$word = $ending2;
	elseif ($char >= 5 || $char == 0)
		$word = $ending3;
	
	// если число больше 10
	if (((int)$count)/10 > 1)
	{
		// работаем со строкой, т.к. $count может быть, например 112
		$char = (int)($count[strlen($count)-2].$count[strlen($count)-1]);
		if ($char > 10 && $char < 15)
			$word = $ending3;
	}
	
	return $with ? $count." ".$word : $word;	
}

// function drawAva - returns img with src $user_id or 'undefined.jpg'
function drawAva($user_id,$big=false){
	
	$path = "/files/img/users/";
	$img = $path.$user_id.($big ? "_big" : "_small");
	$src = is_file(MAIN_DIR.$img.".jpg") ? $img.".jpg" : $path."undefined".($big ? "_big" : "_small").".png";
	return "<img src='$src' />";
}

// function deleteImgs - delete old files from $path with subfolders
function deleteImgs($path){
	
	if (is_dir($path))
	{
		$handle = opendir($path);
		while (false !== ($file = readdir($handle)))
		{
			if ($file != "." && $file != "..")
			{
				if (is_dir($path.DS.$file))
					deleteImgs($path.DS.$file);
				else
					unlink($path.DS.$file);
			}
		}
		closedir($handle);
		rmdir($path);
	}
}

// function showPages - return links with page numbers depending on $count and $limit
function showPages($count, $limit)
{
	global $route;
	if ($count > $limit)
	{
		$max_page = ceil($count/$limit); // всего страниц может быть
		$page = $route->GET('page') ? $route->GET('page') : 1;
		if ($page > $max_page)
			$page = $max_page;
		elseif ($page < 0)
			$page = 1;
		
		$url_query = array();
		$url_arr = parse_url($_SERVER['REQUEST_URI']);
		if (isset($url_arr['query']))
			$url_query = explode("&",$url_arr['query']);
		
		$new_url = $prev_url = $next_url = "?";
		$tmp_arr = array();
		
		// находим page=x или пустые строки и стираем
		for ($z=0; $z<count($url_query); $z++)
			if ((strpos($url_query[$z],"page=") === false) && ($url_query[$z] != ""))
				$tmp_arr[] = $url_query[$z];
		$url_query = $tmp_arr;
		
		// записываем строку обратно
		for ($q=0; $q<count($url_query); $q++)
		{
			$new_url .= $url_query[$q];
			if ($q < count($url_query)-1)
				$new_url .= "&";
		}
		$next_url = $prev_url = $new_url;
		
		if (count($url_query) > 0)
			$next_url = $prev_url .= "&";
		// дописываем страницы
		if ($route->GET('page'))
		{
			$prev_url .= "page=".($page-1);
			$next_url .= "page=".($page+1);
		}
		else
			$next_url .= "page=2";
			
		$next = "";
		$prev = "";
		
		if ($page < $max_page)
			$next = "<a class='page_active' href='".$next_url."'>Следующая &rarr;</a>";
		else
			$next = "<span class='page_inactive'>Следующая &rarr;</span>";
		
		if ($page > 1)
			$prev = "<a class='page_active' href='".$prev_url."'>&larr; Предыдущая</a>";
		else
			$prev = "<span class='page_inactive'>&larr; Предыдущая</span>";

		$str = "<div class='pages_title'>Страницы</div>";
		$str .= "$prev &nbsp;&nbsp;&nbsp;&nbsp; $next";
		$str .= "<div class='pages'>";
		for ($x = 1; $x <= $max_page; $x++)
		{
			if ($x == $page){
				$str .= "<span class='current_page'>".$x."</span>&nbsp;&nbsp;&nbsp;&nbsp;";
			} else {
				$str .= "<a class='page_active' href='".$new_url;
				if (count($url_query) > 0)
					$str .= "&";
				$str .= "page=".$x."'>".$x."</a>&nbsp;&nbsp;&nbsp;&nbsp;";
			}
			
			if ($x%30 == 0)
				$str .= "<br />";
		}
		$str .= "</div>";
		
		return "<div id='pages'>$str</div>";
	}
}

function translitIt($str) 
{
	$tr = array(
		"А"=>"A","Б"=>"B","В"=>"V","Г"=>"G",
		"Д"=>"D","Е"=>"E","Ж"=>"J","З"=>"Z","И"=>"I",
		"Й"=>"Y","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
		"О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
		"У"=>"U","Ф"=>"f","Х"=>"h","Ц"=>"ts","Ч"=>"ch",
		"Ш"=>"Sh","Щ"=>"Sch","Ъ"=>"","Ы"=>"Yi","Ь"=>"",
		"Э"=>"E","Ю"=>"Yu","Я"=>"Ya","а"=>"a","б"=>"b",
		"в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
		"з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
		"м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
		"с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
		"ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
		"ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya", 
		" "=> "-", "."=> "", ","=> "", "/"=> "_", "\""=> "", "'"=> "", ":"=> "", ";"=> "",
		"["=> "", "]"=> "", "("=> "", ")"=> "", "{"=> "", "}"=> "", "«"=> "", "»"=> "",
		"`"=> "", "~"=> "", "!"=> "", "@"=> "", "#"=> "", "$"=> "", "%"=> "", "^"=> "", "&"=> "", "*"=> "", "="=> "", "["=> "", "\\"=> "", "|"=> "", "/"=> "", "<"=> "", ">"=> "", "?"=> ""
	);
	return strtr($str,$tr);
}

?>